//
//  FirstViewController.m
//  XDCommonApp
//
//  Created by XD-XY on 2/12/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "FirstViewController.h"
#import "XDHeader.h"
#import "XDTools.h"
#import "UIButton+Category.h"
#import "UIImageView+WebCache.h"
#import "LeftViewController.h"
#import "LoginViewController.h"
#import "RightViewController.h"
#import "PetQuiltViewCell.h"




#define image_tag 10000
#define IDENTIFIER  @"PetCell"
#define HISTORY @"history"

@interface FirstViewController ()

@end

@implementation FirstViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    DDLOG_CURRENT_METHOD;
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [_scrollView openTimerTask];
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [_scrollView closeTimerTask];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.leftBtn.hidden =YES;
    self.titleLabel.text = @"乐宠俱乐部";
    UIButton *leftBnt = creatXRButton(CGRectMake(5, 23, 35, 35),nil,[UIImage imageNamed:@"Icon.png"],[UIImage imageNamed:@"Icon.png"]);
    leftBnt.tag = UIBUTTON_TAG +1;
    [leftBnt addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:leftBnt];
    UIButton *rightBnt =creatXRButton(CGRectMake(UI_SCREEN_WIDTH -40, 23, 35, 35), nil, [UIImage imageNamed:@"Icon.png"], [UIImage imageNamed:@"Icon.png"]);
    rightBnt.tag =UIBUTTON_TAG +2;
    [rightBnt addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:rightBnt];


    [self initViews];
}
////点击
//-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
//{
//       [_searchBar resignFirstResponder];
//    
//}
- (void)initViews
{
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,2, UI_SCREEN_WIDTH, 30)];
    _searchBar.delegate = self;
    //背景框颜色
    _searchBar.barTintColor = [UIColor whiteColor];
    _searchBar.placeholder = @"搜索版面";
    [self.contentView addSubview:_searchBar];
    [_searchBar setSearchFieldBackgroundImage:[UIImage imageNamed:@"home_04.png"] forState:UIControlStateNormal];

    _scrollView = [[PostsScrollView alloc] initPageScrollView:CGRectMake(0, height_y(_searchBar)+2, UI_SCREEN_WIDTH, 120) pageControllerFrame:CGRectMake(260, 55, 60, 10) backgroudImage:nil pageNumber:3];
    _scrollView.delegate = self;
    _scrollView.imageUrlArray = nil;
    _scrollView.backgroundColor = [UIColor blueColor];
    [self.contentView addSubview:_scrollView];

    _dataArray = [[NSMutableArray alloc] init];
    //初始化
    _quiltView = [[TMQuiltView alloc] initWithFrame:CGRectMake(0, height_y(_scrollView), 320, 309)];
    _quiltView.delegate = self;
    _quiltView.dataSource = self;
    [self.contentView addSubview:_quiltView];
    _quiltView.backgroundColor = [UIColor whiteColor];

    _footerView = [MJRefreshFooterView footer];
    _footerView.delegate = self;
    _footerView.scrollView = _quiltView;

    _headerView = [MJRefreshHeaderView header];
    _headerView.delegate = self;
    _headerView.scrollView = _quiltView;

    [self loadData];

}
- (void)loadData
{
    for (int i = 0; i < 10; i ++) {
        NSDictionary *dic = @{@"image":[NSString stringWithFormat:@"%d.jpeg",i+1],@"title":@"瞧瞧我家的小泰迪像不像小大人！"};
        [_dataArray addObject:dic];
    }
    [_quiltView reloadData];
}

#pragma mark---TMQuiltView-------
//数据个数
-(NSInteger)quiltViewNumberOfCells:(TMQuiltView *)TMQuiltView
{
    NSLog(@"count:%d-----array:%@",_dataArray.count,_dataArray);
    return _dataArray.count;
}

-(TMQuiltViewCell *)quiltView:(TMQuiltView *)quiltView cellAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifierStr = IDENTIFIER;
    PetQuiltViewCell *cell = (PetQuiltViewCell *)[quiltView dequeueReusableCellWithReuseIdentifier:identifierStr];
    if (!cell)
    {
        cell = [[PetQuiltViewCell alloc] initWithReuseIdentifier:identifierStr];
    }
    cell.picIV.image = nil;
    cell.titleLB.text = nil;
    //    cell.picIV.frame = CGRectMake(0, 0, 150, [self quiltView:_quiltView heightForCellAtIndexPath:indexPath]-50);
    ////    [cell.picIV setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://imgur.com/%@%@", [item objectForKey:@"hash"], [item objectForKey:@"ext"]]]];
    //    cell.picIV.image = [self imageAtIndexPath:indexPath];
    //    cell.titleLB.text = _dataArray[indexPath.row][@"title"];
    //    cell.titleLB.frame = CGRectMake(0, cell.picIV.frame.origin.y + cell.picIV.frame.size.height, 150, 50);
    [cell cellForIndexPath:indexPath andItem:_dataArray[indexPath.row] height:[self quiltView:_quiltView heightForCellAtIndexPath:indexPath]];
    return cell;
}
- (CGFloat)imageHeightAtIndexPath:(NSIndexPath *)indexPath
{

    float height = ([_dataArray[indexPath.row][@"height"] floatValue]*160)/([_dataArray[indexPath.row][@"height"] floatValue] == 0?1:[_dataArray[indexPath.row][@"height"] floatValue]);
    //    NSLog(@"%f----%f",[_dataArray[indexPath.row][@"height"] floatValue],[_dataArray[indexPath.row][@"height"] floatValue]);
    //    NSLog(@"imageHeight:%f",height);
    return  height;
}

- (UIImage *)imageAtIndexPath:(NSIndexPath *)indexPath
{
    return  [UIImage imageNamed:[[_dataArray objectAtIndex:indexPath.row] objectForKey:@"image"]];
}
#pragma mark -
#pragma mark TMQuiltViewDelegate
//列数
- (NSInteger)quiltViewNumberOfColumns:(TMQuiltView *)quiltView
{
    return 2;
}
//单元高度
- (CGFloat)quiltView:(TMQuiltView *)quiltView heightForCellAtIndexPath:(NSIndexPath *)indexPath {

    //    float height = [self imageHeightAtIndexPath:indexPath] + 20.0;
    //    //NSLog(@"height:%f",height);
    //    return height;

    float height = [self imageAtIndexPath:indexPath].size.height / [self quiltViewNumberOfColumns:quiltView];
    return indexPath.row == 3 ? 80 : height  + 65;
}
//点击
- (void)quiltView:(TMQuiltView *)quiltView didSelectCellAtIndexPath:(NSIndexPath *)indexPath{

    NSLog(@"row:%d",indexPath.row);
    [_searchBar resignFirstResponder];
//    SecondViewController *sendVC = [[SecondViewController alloc] init];
//    [self.navigationController pushViewController:sendVC animated:YES];
}


#pragma mark -- MJRefresh----

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    [_headerView endRefreshing];
    [_footerView endRefreshing];
}
-(void)refreshViewEndRefreshing:(MJRefreshBaseView *)refreshView
{

}
-(void)refreshView:(MJRefreshBaseView *)refreshView stateChange:(MJRefreshState)state
{
    
}

#pragma mark  BUTTON CLICK SEL
-(void)buttonClick:(UIButton *)sender{
    if(sender.tag == UIBUTTON_TAG +1){
        LeftViewController *leftVC=[[LeftViewController alloc]init];
        UINavigationController *nav=[[UINavigationController alloc]initWithRootViewController:leftVC];
        nav.hidesBottomBarWhenPushed =YES;
//        [self.navigationController pushViewController:leftVC animated:YES];
        ////注释 推入抽屉效果界面的方法
        [self theDrawerToViewController:nav leftOrRight:LEFT_VIEWCONTROLLER];
    }else{
        if(0){
            RightViewController *rightVC=[[RightViewController alloc]init];
            [self theDrawerToViewController:rightVC leftOrRight:RIGHT_VIEWCONTROLLER];
        }else{
            LoginViewController *loginVC=[[LoginViewController alloc]init];
            UINavigationController  *nav=[[UINavigationController alloc]initWithRootViewController:loginVC];
            nav.navigationBarHidden = YES;
            [self theDrawerToViewController:nav leftOrRight:RIGHT_VIEWCONTROLLER];
//            [self.navigationController pushViewController:loginVC animated:YES];
        }
    }
}
-(void)theDrawerToViewController:(UIViewController *)controller leftOrRight:(NSInteger )type{
    if(type == LEFT_VIEWCONTROLLER){
        [self.revealSideViewController pushViewController:controller onDirection:PPRevealSideDirectionLeft withOffset:80 animated:YES];
    }else{
        [self.revealSideViewController pushViewController:controller onDirection:PPRevealSideDirectionRight withOffset:80 animated:YES];

    }
}
-(void)viewWillDisappear:(BOOL)animated
{
    DDLOG_CURRENT_METHOD;    
}
- (void)createRecommendView{

    if (_recommendView == nil) {
        _recommendView = [[UIView alloc] initWithFrame:CGRectMake(0, height_y(_removeBtn), 320, 120)];
        _recommendView.backgroundColor = [UIColor whiteColor];
    }
    else{
        _recommendView.hidden = NO;
        _recommendView.frame = CGRectMake(0, height_y(_removeBtn), 320, 120);
        for (UIView *subView in _recommendView.subviews) {
            [subView removeFromSuperview];
        }
    }
    [self.contentView addSubview:_recommendView];
    NSArray *array = @[@"search_04.png",@"search_05.png",@"search_06.png",@"search_07.png",@"search_08.png"];
    NSArray *titleArray = @[@"可爱怪",@"毛毛多",@"泰迪犬",@"小公主",@"喵星人"];
    for (int i = 0; i < 5; i ++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(i%2?230:10, 10 + i/2*32, 70, 22);
        [btn setBackgroundImage:[UIImage imageNamed:array[i]] forState:UIControlStateNormal];
        [btn setTitle:titleArray[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.tag = 100 + i;
        [btn addTarget: self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
        [_recommendView addSubview:btn];
    }
}
- (void)clickAction:(UIButton *)btn
{

}
- (void) initTableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, height_y(_searchBar), UI_SCREEN_WIDTH, 100) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        [self.contentView addSubview:_tableView];
    }
    else{
        _tableView.hidden = NO;
        _tableView.frame = CGRectMake(0, height_y(_searchBar), UI_SCREEN_WIDTH, 100);
    }
    _removeBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    _removeBtn.frame = CGRectMake(0, height_y(_tableView), 320, 35);
    [_removeBtn setTitle:@"清除历史记录" forState:UIControlStateNormal];
    [_removeBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [_removeBtn addTarget:self action:@selector(removeHistory) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:_removeBtn];
    [self createRecommendView];
    [self loadTableViewData];
}
- (void)removeHistory
{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    [def removeObjectForKey:HISTORY];
    [def synchronize];
    [_historyArray removeAllObjects];
    [_tableView reloadData];
    _tableView.frame = CGRectMake(0, height_y(_searchBar), 0, 0);
    _removeBtn.frame = CGRectMake(0, height_y(_tableView), 0, 0);
    [UIView animateWithDuration:0.5 animations:^{
        _recommendView.frame = CGRectMake(0, height_y(_removeBtn), 320, 120);

    }];

}
- (void)loadTableViewData
{
    if (_historyArray == nil) {
        _historyArray = [[NSMutableArray alloc] init];
    }
    else{
        if (_historyArray.count != 0) {
            [_historyArray removeAllObjects];
        }
    }
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSArray *array = [def objectForKey:HISTORY];
    if (array.count != 0) {
        _historyArray = [NSMutableArray arrayWithArray:array];
        [_tableView reloadData];
    }
    else
    {
        _tableView.frame = CGRectMake(0, height_y(_searchBar), 0, 0);
        _removeBtn.frame = CGRectMake(0, height_y(_tableView), 0, 0);
        _recommendView.frame = CGRectMake(0, height_y(_removeBtn), 0, 0);
    }

}
#pragma mark---SearchBar---
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [_searchBar setShowsCancelButton:YES animated:YES];
    _quiltView.hidden = YES;
    _scrollView.hidden = YES;
    [self initTableView];
    return YES;
}

-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    [_searchBar setShowsCancelButton:NO animated:YES];
    return YES;
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [_searchBar resignFirstResponder];
    _quiltView.hidden = NO;
    _scrollView.hidden = NO;

    _tableView.hidden = YES;
    _removeBtn.hidden = YES;
    _recommendView.hidden = YES;
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSArray *array = [def objectForKey:HISTORY];
    NSMutableArray *historyArr = [NSMutableArray arrayWithArray:array];
    [historyArr addObject:searchBar.text];
    [def setObject:historyArr forKey:HISTORY];
    [def synchronize];

    _quiltView.hidden = NO;
    _scrollView.hidden = NO;

    _tableView.hidden = YES;
    _removeBtn.hidden = YES;
    _recommendView.hidden = YES;
    _searchBar.text = nil;


}

#pragma mark-----tableView-----
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _historyArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellName = @"historyCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
    }
    cell.textLabel.text = [_historyArray objectAtIndex:indexPath.row];

    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 35;
}
-(void)gestureClick:(UITapGestureRecognizer *)sender{

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
